Python provides %
as String formatting operator, which has to be used with C
style format specifiers. General usage of this operator is as follows.
result = format_string % collection_of_items
Now Let's see the Formatting Operator in action
In [16]:
'8 = %d , 8.5 = %.1f, name = %s, 3 = %04d' % (8, 8.5, 'Ravi', 3)
Out[16]:
There is one more way to format, without the hassle of remembering the format specifiers. You can use format()
method of the current string. Same output of above example can be obtained as follows
In [18]:
'8 = {}, 8.5 = {}, name = {}, 3 = {:04}'.format(8, 8.5, 'Ravi', 3)
Out[18]:
If the number of items to be formatted goes long, it would become hard to remember their positions. You can name each entry in format string, and refer to them in the call to format()
as shown below. Note that the order of items can be changed now as the items are only referred by name.
In [19]:
'8 = {a}, 8.5 = {b}, name = {c}, 3 = {d:04}'.format(a = 8, c = 'Ravi', d = 3, b = 8.5)
Out[19]: